﻿using SuperX.Common.Log;
using SuperX.Common.PlugIn;
using SuperX.Common.Respository;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace SuperX.Common
{
    // 
    public class ProjectInfo
    {
        // 
        public string Name { get; set; }

        // 
        public DateTime CreateTime { get; set; }

        // 
        public string Creator { get; set; }

        // 
        public DateTime ModifyTime { get; set; }

        // 
        public string Modifier { get; set; }

        // 
        public string ProjVersion { get; set; }

        // 
        public string ProductVersion { get; set; }

        // 
        public string Guid { get; set; }

        // 
        public SuperX.Common.PlugIn.RunMode ProjectMode { get; set; }

        /// <summary>
        /// 工程主从状态
        /// </summary>
        public ProjectState ProjectState { get; set; }

        //
        public string Password { get; set; }

        // 
        public string Description { get; set; }

        // 
        public List<ModuleInfo> Services
        {
            get
            {
                List<ModuleInfo> result;
                if ((result = this._modules) == null)
                {
                    result = (this._modules = new List<ModuleInfo>());
                }
                return result;
            }
            set
            {
                this._modules = value;
            }
        }

        // 
        public static bool RegisterPlugIn(ModuleSysInfo moduleInfo)
        {
            if (moduleInfo == null || string.IsNullOrEmpty(moduleInfo.Name) || string.IsNullOrEmpty(moduleInfo.CfgName) || string.IsNullOrEmpty(moduleInfo.ServiceType))
            {
                return false;
            }
            List<ModuleSysInfo> systemPlugIns = ProjectInfo.GetSystemPlugIns();
            if (systemPlugIns.FirstOrDefault((ModuleSysInfo m) => m.Name == moduleInfo.Name) != null)
            {
                return false;
            }
            systemPlugIns.Add(moduleInfo);
            JsonRepository jsonRepository = new JsonRepository(AppCommonString.ModuleCfgPath, systemPlugIns, false);
            bool result;
            try
            {
                jsonRepository.Save();
                result = true;
            }
            catch (Exception)
            {
                result = false;
            }
            return result;
        }

        /// <summary>
        /// 获取所有系统模组
        /// </summary>
        /// <returns></returns>
        public static List<ModuleSysInfo> GetAllPlugIns()
        {
            List<ModuleSysInfo> systemPlugIns = ProjectInfo.GetSystemPlugIns();
            systemPlugIns.AddRange(ProjectInfo.GetCustomPlugIns());
            return systemPlugIns;
        }

        /// <summary>
        /// 获取所有自定义模组
        /// </summary>
        /// <returns></returns>
        public static List<ModuleSysInfo> GetSystemPlugIns()
        {
            JsonRepository jsonRepository = new JsonRepository("Services.appcfg");
            jsonRepository.Load(typeof(List<ModuleSysInfo>));
            return (jsonRepository.Model as List<ModuleSysInfo>) ?? new List<ModuleSysInfo>();
        }

        // 
        public static List<ModuleSysInfo> GetCustomPlugIns()
        {
            JsonRepository jsonRepository = new JsonRepository("CustomModules.appcfg");
            jsonRepository.Load(typeof(List<ModuleSysInfo>));
            return (jsonRepository.Model as List<ModuleSysInfo>) ?? new List<ModuleSysInfo>();
        }

        // 
        public static ProjectInfo CreateProject(string projectName, string description, string plugIns)
        {
            ProjectInfo projectInfo = ProjectInfo.InitProjectConfig(projectName, description, new ProjectInfo());
            List<ModuleSysInfo> systemPlugIns = ProjectInfo.GetSystemPlugIns();
            if (plugIns == "*")
            {
                foreach (ModuleSysInfo moduleSysInfo in systemPlugIns)
                {
                    projectInfo.Services.Add(ProjectInfo.ConvertToModuleInfo(moduleSysInfo));
                }
                return projectInfo;
            }
            string[] array = plugIns.Split(new char[]
            {
                ','
            });
            for (int i = 0; i < array.Length; i++)
            {
                string plugInName = array[i];
                ModuleSysInfo moduleSysInfo2 = systemPlugIns.FirstOrDefault((ModuleSysInfo m) => m.Name == plugInName);
                if (moduleSysInfo2 != null)
                {
                    projectInfo.Services.Add(ProjectInfo.ConvertToModuleInfo(moduleSysInfo2));
                }
            }
            return projectInfo;
        }

        // 
        private static ModuleInfo ConvertToModuleInfo(ModuleSysInfo moduleSysInfo)
        {
            if (moduleSysInfo == null)
            {
                return null;
            }
            return new ModuleInfo
            {
                Name = moduleSysInfo.Name,
                Description = moduleSysInfo.Description,
                CfgName = moduleSysInfo.CfgName,
                IsEnable = moduleSysInfo.IsEnable,
                RunMode = moduleSysInfo.RunMode,
                ServiceType = moduleSysInfo.ServiceType,
            };
        }

        // 
        public static ProjectInfo CreateProjectByTemplate(string projectName, string description, string templatePath)
        {
            if (!File.Exists(templatePath))
            {
                return null;
            }
            JsonRepository jsonRepository = new JsonRepository(templatePath);
            jsonRepository.Load(typeof(ProjectInfo));
            ProjectInfo projectInfo = jsonRepository.Model as ProjectInfo;
            return ProjectInfo.InitProjectConfig(projectName, description, projectInfo);
        }

        // 
        public static ProjectInfo CreateDefaultProject(string projectName, string description)
        {
            ProjectInfo projectInfo = ProjectInfo.InitProjectConfig(projectName, description, new ProjectInfo());
            JsonRepository jsonRepository = new JsonRepository(AppCommonString.ModuleCfgPath);
            jsonRepository.Load(typeof(List<ModuleSysInfo>));
            List<ModuleSysInfo> list = jsonRepository.Model as List<ModuleSysInfo>;
            if (list == null)
            {
                Logger.Error(string.Format("\"{0}\"文件不存在模组信息", AppCommonString.ModuleCfgPath));
                return null;
            }
            foreach (ModuleSysInfo moduleSysInfo in list)
            {
                projectInfo.Services.Add(new ModuleInfo
                {
                    Name = moduleSysInfo.Name,
                    Description = moduleSysInfo.Description,
                    CfgName = moduleSysInfo.CfgName,
                    IsEnable = moduleSysInfo.IsEnable,
                    RunMode = projectInfo.ProjectMode,
                    ServiceType = moduleSysInfo.ServiceType,
                    RunIndex = moduleSysInfo.RunIndex
                });
            }
            return projectInfo;
        }

        // 
        private static ProjectInfo InitProjectConfig(string projectName, string description, ProjectInfo projectInfo)
        {
            if (projectInfo == null)
            {
                return null;
            }
            projectInfo.Name = ((!string.IsNullOrWhiteSpace(projectName)) ? projectName : ("Project" + DateTime.Now.ToString("yyMMddHHmmss")));
            projectInfo.Description = description;
            projectInfo.CreateTime = DateTime.Now;
            projectInfo.ModifyTime = DateTime.Now;
            projectInfo.Guid = System.Guid.NewGuid().ToString();
            projectInfo.ProjVersion = "0.1";
            projectInfo.ProductVersion = AppCommonString.ProductVersion;
            projectInfo.Creator = Environment.UserName;
            projectInfo.Modifier = Environment.UserName;
            return projectInfo;
        }

        private List<ModuleInfo> _modules;
    }
}
